<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>A Guide to Active Record Associations</title>
  <!--[if lt IE 8]>
  <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
  <![endif]-->
  <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
  <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
  <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
</head>
<body>
  <div id="header" >
    <div id="logo">
      <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
    </div>

    <h1 id="site_title"><span>Ruby on Rails</span></h1>
    <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>

    <ul id="navMain">
      <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
      <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
    </ul>
  </div>

  <div id="container">
    
    <div id="sidebar">
      <h2>Chapters</h2>
      <ol>
          <li>
          <a href="#_why_associations">Why Associations?</a>
          </li>
          <li>
          <a href="#_the_types_of_associations">The Types of Associations</a>
            <ul>
            
              <li><a href="#_the_tt_belongs_to_tt_association">The <tt>belongs_to</tt> Association</a></li>
            
              <li><a href="#_the_tt_has_one_tt_association">The <tt>has_one</tt> Association</a></li>
            
              <li><a href="#_the_tt_has_many_tt_association">The <tt>has_many</tt> Association</a></li>
            
              <li><a href="#_the_tt_has_many_through_tt_association">The <tt>has_many :through</tt> Association</a></li>
            
              <li><a href="#_the_tt_has_one_through_tt_association">The <tt>has_one :through</tt> Association</a></li>
            
              <li><a href="#_the_tt_has_and_belongs_to_many_tt_association">The <tt>has_and_belongs_to_many</tt> Association</a></li>
            
              <li><a href="#_choosing_between_tt_belongs_to_tt_and_tt_has_one_tt">Choosing Between <tt>belongs_to</tt> and <tt>has_one</tt></a></li>
            
              <li><a href="#_choosing_between_tt_has_many_through_tt_and_tt_has_and_belongs_to_many_tt">Choosing Between <tt>has_many :through</tt> and <tt>has_and_belongs_to_many</tt></a></li>
            
              <li><a href="#_polymorphic_associations">Polymorphic Associations</a></li>
            
              <li><a href="#_self_joins">Self Joins</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_tips_tricks_and_warnings">Tips, Tricks, and Warnings</a>
            <ul>
            
              <li><a href="#_controlling_caching">Controlling Caching</a></li>
            
              <li><a href="#_avoiding_name_collisions">Avoiding Name Collisions</a></li>
            
              <li><a href="#_updating_the_schema">Updating the Schema</a></li>
            
              <li><a href="#_controlling_association_scope">Controlling Association Scope</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_detailed_association_reference">Detailed Association Reference</a>
            <ul>
            
              <li><a href="#_the_tt_belongs_to_tt_association_2">The <tt>belongs_to</tt> Association</a></li>
            
              <li><a href="#_the_has_one_association">The has_one Association</a></li>
            
              <li><a href="#_the_has_many_association">The has_many Association</a></li>
            
              <li><a href="#_the_tt_has_and_belongs_to_many_tt_association_2">The <tt>has_and_belongs_to_many</tt> Association</a></li>
            
              <li><a href="#_association_callbacks">Association Callbacks</a></li>
            
              <li><a href="#_association_extensions">Association Extensions</a></li>
            
            </ul>
          </li>
          <li>
          <a href="#_changelog">Changelog</a>
          </li>
      </ol>
    </div>
    
    <div id="content">
        <h1>A Guide to Active Record Associations</h1>
      <div id="preamble">
<div class="sectionbody">
<div class="paragraph"><p>This guide covers the association features of Active Record. By referring to this guide, you will be able to:</p></div>
<div class="ulist"><ul>
<li>
<p>
Declare associations between Active Record models
</p>
</li>
<li>
<p>
Understand the various types of Active Record associations
</p>
</li>
<li>
<p>
Use the methods added to your models by creating associations
</p>
</li>
</ul></div>
</div>
</div>
<h2 id="_why_associations">1. Why Associations?</h2>
<div class="sectionbody">
<div class="paragraph"><p>Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Now, suppose we wanted to add a new order for an existing customer. We&#8217;d need to do something like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order</span> <span style="color: #990000">=</span> Order<span style="color: #990000">.</span>create<span style="color: #990000">(:</span>order_date <span style="color: #990000">=&gt;</span> Time<span style="color: #990000">.</span>now<span style="color: #990000">,</span> <span style="color: #990000">:</span>customer_id <span style="color: #990000">=&gt;</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>id<span style="color: #990000">)</span></tt></pre></div></div>
<div class="paragraph"><p>Or consider deleting a customer, and ensuring that all of its orders get deleted as well:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@orders</span> <span style="color: #990000">=</span> Order<span style="color: #990000">.</span>find_by_customer_id<span style="color: #990000">(</span><span style="color: #009900">@customer</span><span style="color: #990000">.</span>id<span style="color: #990000">)</span>
<span style="color: #009900">@orders</span><span style="color: #990000">.</span>each <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>order<span style="color: #990000">|</span>
  order<span style="color: #990000">.</span>destroy
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="color: #009900">@customer</span><span style="color: #990000">.</span>destroy</tt></pre></div></div>
<div class="paragraph"><p>With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here&#8217;s the revised code for setting up customers and orders:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>With this change, creating a new order for a particular customer is easier:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>create<span style="color: #990000">(:</span>order_date <span style="color: #990000">=&gt;</span> Time<span style="color: #990000">.</span>now<span style="color: #990000">)</span></tt></pre></div></div>
<div class="paragraph"><p>Deleting a customer and all of its orders is <em>much</em> easier:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span><span style="color: #990000">.</span>destroy</tt></pre></div></div>
<div class="paragraph"><p>To learn more about the different types of associations, read the next section of this Guide. That&#8217;s followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.</p></div>
</div>
<h2 id="_the_types_of_associations">2. The Types of Associations</h2>
<div class="sectionbody">
<div class="paragraph"><p>In Rails, an <em>association</em> is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model <tt>belongs_to</tt> another, you instruct Rails to maintain Primary Key-Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>belongs_to</tt>
</p>
</li>
<li>
<p>
<tt>has_one</tt>
</p>
</li>
<li>
<p>
<tt>has_many</tt>
</p>
</li>
<li>
<p>
<tt>has_many :through</tt>
</p>
</li>
<li>
<p>
<tt>has_one :through</tt>
</p>
</li>
<li>
<p>
<tt>has_and_belongs_to_many</tt>
</p>
</li>
</ul></div>
<div class="paragraph"><p>In the remainder of this guide, you&#8217;ll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.</p></div>
<h3 id="_the_tt_belongs_to_tt_association">2.1. The <tt>belongs_to</tt> Association</h3>
<div class="paragraph"><p>A <tt>belongs_to</tt> association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you&#8217;d declare the order model this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p><span class="image">
<img src="images/belongs_to.png" alt="belongs_to Association Diagram" title="belongs_to Association Diagram" />
</span></p></div>
<h3 id="_the_tt_has_one_tt_association">2.2. The <tt>has_one</tt> Association</h3>
<div class="paragraph"><p>A <tt>has_one</tt> association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you&#8217;d declare the supplier model like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p><span class="image">
<img src="images/has_one.png" alt="has_one Association Diagram" title="has_one Association Diagram" />
</span></p></div>
<h3 id="_the_tt_has_many_tt_association">2.3. The <tt>has_many</tt> Association</h3>
<div class="paragraph"><p>A <tt>has_many</tt> association indicates a one-to-many connection with another model. You&#8217;ll often find this association on the "other side" of a <tt>belongs_to</tt> association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">The name of the other model is pluralized when declaring a <tt>has_many</tt> association.</td>
</tr></table>
</div>
<div class="paragraph"><p><span class="image">
<img src="images/has_many.png" alt="has_many Association Diagram" title="has_many Association Diagram" />
</span></p></div>
<h3 id="_the_tt_has_many_through_tt_association">2.4. The <tt>has_many :through</tt> Association</h3>
<div class="paragraph"><p>A <tt>has_many :through</tt> association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding <em>through</em> a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Physician <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>appointments
  has_many <span style="color: #990000">:</span>patients<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>appointments
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Appointment <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>physician
  belongs_to <span style="color: #990000">:</span>patient
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Patient <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>appointments
  has_many <span style="color: #990000">:</span>physicians<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>appointments
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p><span class="image">
<img src="images/has_many_through.png" alt="has_many :through Association Diagram" title="has_many :through Association Diagram" />
</span></p></div>
<div class="paragraph"><p>The <tt>has_many :through</tt> association is also useful for setting up "shortcuts" through nested :<tt>has_many</tt> associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Document <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>sections
  has_many <span style="color: #990000">:</span>paragraphs<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>sections
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Section <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>document
  has_many <span style="color: #990000">:</span>paragraphs
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Paragraph <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>section
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h3 id="_the_tt_has_one_through_tt_association">2.5. The <tt>has_one :through</tt> Association</h3>
<div class="paragraph"><p>A <tt>has_one :through</tt> association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding <em>through</em> a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account
  has_one <span style="color: #990000">:</span>account_history<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>supplier
  has_one <span style="color: #990000">:</span>account_history
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AccountHistory <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p><span class="image">
<img src="images/has_one_through.png" alt="has_one :through Association Diagram" title="has_one :through Association Diagram" />
</span></p></div>
<h3 id="_the_tt_has_and_belongs_to_many_tt_association">2.6. The <tt>has_and_belongs_to_many</tt> Association</h3>
<div class="paragraph"><p>A <tt>has_and_belongs_to_many</tt> association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Assembly <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>parts
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Part <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p><span class="image">
<img src="images/habtm.png" alt="has_and_belongs_to_many Association Diagram" title="has_and_belongs_to_many Association Diagram" />
</span></p></div>
<h3 id="_choosing_between_tt_belongs_to_tt_and_tt_has_one_tt">2.7. Choosing Between <tt>belongs_to</tt> and <tt>has_one</tt></h3>
<div class="paragraph"><p>If you want to set up a 1-1 relationship between two models, you&#8217;ll need to add <tt>belongs_to</tt> to one, and <tt>has_one</tt> to the other. How do you know which is which?</p></div>
<div class="paragraph"><p>The distinction is in where you place the foreign key (it goes on the table for the class declaring the <tt>belongs_to</tt> association), but you should give some thought to the actual meaning of the data as well. The <tt>has_one</tt> relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>supplier
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The corresponding migration might look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreateSuppliers <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
    create_table <span style="color: #990000">:</span>suppliers <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>string  <span style="color: #990000">:</span>name
      t<span style="color: #990000">.</span>timestamps
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

    create_table <span style="color: #990000">:</span>accounts <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>integer <span style="color: #990000">:</span>supplier_id
      t<span style="color: #990000">.</span>string  <span style="color: #990000">:</span>account_number
      t<span style="color: #990000">.</span>timestamps
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
    drop_table <span style="color: #990000">:</span>accounts
    drop_table <span style="color: #990000">:</span>suppliers
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">Using <tt>t.integer :supplier_id</tt> makes the foreign key naming obvious and implicit. In current versions of Rails, you can abstract away this implementation detail by using <tt>t.references :supplier</tt> instead.</td>
</tr></table>
</div>
<h3 id="_choosing_between_tt_has_many_through_tt_and_tt_has_and_belongs_to_many_tt">2.8. Choosing Between <tt>has_many :through</tt> and <tt>has_and_belongs_to_many</tt></h3>
<div class="paragraph"><p>Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use <tt>has_and_belongs_to_many</tt>, which allows you to make the association directly:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Assembly <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>parts
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Part <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The second way to declare a many-to-many relationship is to use <tt>has_many :through</tt>. This makes the association indirectly, through a join model:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Assembly <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>manifests
  has_many <span style="color: #990000">:</span>parts<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>manifests
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Manifest <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>assembly
  belongs_to <span style="color: #990000">:</span>part
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Part <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>manifests
  has_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>manifests
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The simplest rule of thumb is that you should set up a <tt>has_many :through</tt> relationship if you need to work with the relationship model as an independent entity. If you don&#8217;t need to do anything with the relationship model, it may be simpler to set up a <tt>has_and_belongs_to_many</tt> relationship (though you&#8217;ll need to remember to create the joining table).</p></div>
<div class="paragraph"><p>You should use <tt>has_many :through</tt> if you need validations, callbacks, or extra attributes on the join model.</p></div>
<h3 id="_polymorphic_associations">2.9. Polymorphic Associations</h3>
<div class="paragraph"><p>A slightly more advanced twist on associations is the <em>polymorphic association</em>. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here&#8217;s how this could be declared:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Picture <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>imageable<span style="color: #990000">,</span> <span style="color: #990000">:</span>polymorphic <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Employee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>pictures<span style="color: #990000">,</span> <span style="color: #990000">:</span>as <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>imageable
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Product <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>pictures<span style="color: #990000">,</span> <span style="color: #990000">:</span>as <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>imageable
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>You can think of a polymorphic <tt>belongs_to</tt> declaration as setting up an interface that any other model can use. From an instance of the <tt>Employee</tt> model, you can retrieve a collection of pictures: <tt>@employee.pictures</tt>. Similarly, you can retrieve <tt>@product.pictures</tt>. If you have an instance of the <tt>Picture</tt> model, you can get to its parent via <tt>@picture.imageable</tt>. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreatePictures <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
    create_table <span style="color: #990000">:</span>pictures <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>string  <span style="color: #990000">:</span>name
      t<span style="color: #990000">.</span>integer <span style="color: #990000">:</span>imageable_id
      t<span style="color: #990000">.</span>string  <span style="color: #990000">:</span>imageable_type
      t<span style="color: #990000">.</span>timestamps
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
    drop_table <span style="color: #990000">:</span>pictures
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>This migration can be simplified by using the <tt>t.references</tt> form:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreatePictures <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
    create_table <span style="color: #990000">:</span>pictures <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>string  <span style="color: #990000">:</span>name
      t<span style="color: #990000">.</span>references <span style="color: #990000">:</span>imageable<span style="color: #990000">,</span> <span style="color: #990000">:</span>polymorphic <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
      t<span style="color: #990000">.</span>timestamps
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
    drop_table <span style="color: #990000">:</span>pictures
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p><span class="image">
<img src="images/polymorphic.png" alt="Polymorphic Association Diagram" title="Polymorphic Association Diagram" />
</span></p></div>
<h3 id="_self_joins">2.10. Self Joins</h3>
<div class="paragraph"><p>In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as manager and subordinates. This situation can be modeled with self-joining associations:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Employee <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>subordinates<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Employee"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"manager_id"</span>
  belongs_to <span style="color: #990000">:</span>manager<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Employee"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>With this setup, you can retrieve <tt>@employee.subordinates</tt> and <tt>@employee.manager</tt>.</p></div>
</div>
<h2 id="_tips_tricks_and_warnings">3. Tips, Tricks, and Warnings</h2>
<div class="sectionbody">
<div class="paragraph"><p>Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:</p></div>
<div class="ulist"><ul>
<li>
<p>
Controlling caching
</p>
</li>
<li>
<p>
Avoiding name collisions
</p>
</li>
<li>
<p>
Updating the schema
</p>
</li>
<li>
<p>
Controlling association scope
</p>
</li>
</ul></div>
<h3 id="_controlling_caching">3.1. Controlling Caching</h3>
<div class="paragraph"><p>All of the association methods are built around caching that keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>customer<span style="color: #990000">.</span>orders                 <span style="font-style: italic"><span style="color: #9A1900"># retrieves orders from the database</span></span>
customer<span style="color: #990000">.</span>orders<span style="color: #990000">.</span>size            <span style="font-style: italic"><span style="color: #9A1900"># uses the cached copy of orders</span></span>
customer<span style="color: #990000">.</span>orders<span style="color: #990000">.</span>empty?          <span style="font-style: italic"><span style="color: #9A1900"># uses the cached copy of orders</span></span></tt></pre></div></div>
<div class="paragraph"><p>But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass <tt>true</tt> to the association call:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>customer<span style="color: #990000">.</span>orders                 <span style="font-style: italic"><span style="color: #9A1900"># retrieves orders from the database</span></span>
customer<span style="color: #990000">.</span>orders<span style="color: #990000">.</span>size            <span style="font-style: italic"><span style="color: #9A1900"># uses the cached copy of orders</span></span>
customer<span style="color: #990000">.</span>orders<span style="color: #990000">(</span><span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">).</span>empty?    <span style="font-style: italic"><span style="color: #9A1900"># discards the cached copy of orders and goes back to the database</span></span></tt></pre></div></div>
<h3 id="_avoiding_name_collisions">3.2. Avoiding Name Collisions</h3>
<div class="paragraph"><p>You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of <tt>ActiveRecord::Base</tt>. The association method would override the base method and break things. For instance, <tt>attributes</tt> or <tt>connection</tt> are bad names for associations.</p></div>
<h3 id="_updating_the_schema">3.3. Updating the Schema</h3>
<div class="paragraph"><p>Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For <tt>belongs_to</tt> associations you need to create foreign keys, and for <tt>has_and_belongs_to_many</tt> associations you need to create the appropriate join table.</p></div>
<h4 id="_creating_foreign_keys_for_tt_belongs_to_tt_associations">3.3.1. Creating Foreign Keys for <tt>belongs_to</tt> Associations</h4>
<div class="paragraph"><p>When you declare a <tt>belongs_to</tt> association, you need to create foreign keys as appropriate. For example, consider this model:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>This declaration needs to be backed up by the proper foreign key declaration on the orders table:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreateOrders <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
    create_table <span style="color: #990000">:</span>orders <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>datetime   <span style="color: #990000">:</span>order_date
      t<span style="color: #990000">.</span>string     <span style="color: #990000">:</span>order_number
      t<span style="color: #990000">.</span>integer    <span style="color: #990000">:</span>customer_id
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
    drop_table <span style="color: #990000">:</span>orders
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>If you create an association some time after you build the underlying model, you need to remember to create an <tt>add_column</tt> migration to provide the necessary foreign key.</p></div>
<h4 id="_creating_join_tables_for_tt_has_and_belongs_to_many_tt_associations">3.3.2. Creating Join Tables for <tt>has_and_belongs_to_many</tt> Associations</h4>
<div class="paragraph"><p>If you create a <tt>has_and_belongs_to_many</tt> association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the <tt>:join_table</tt> option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">The precedence between model names is calculated using the <tt>&lt;</tt> operator for <tt>String</tt>. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers".</td>
</tr></table>
</div>
<div class="paragraph"><p>Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Assembly <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>parts
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Part <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>These need to be backed up by a migration to create the <tt>assemblies_parts</tt> table. This table should be created without a primary key:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CreateAssemblyPartJoinTable <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Migration
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>up
    create_table <span style="color: #990000">:</span>assemblies_parts<span style="color: #990000">,</span> <span style="color: #990000">:</span>id <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span> <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>t<span style="color: #990000">|</span>
      t<span style="color: #990000">.</span>integer <span style="color: #990000">:</span>assembly_id
      t<span style="color: #990000">.</span>integer <span style="color: #990000">:</span>part_id
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>down
    drop_table <span style="color: #990000">:</span>assemblies_parts
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h3 id="_controlling_association_scope">3.4. Controlling Association Scope</h3>
<div class="paragraph"><p>By default, associations look for objects only within the current module&#8217;s scope. This can be important when you declare Active Record models within a module. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> MyApplication
  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Business
    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       has_one <span style="color: #990000">:</span>account
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       belongs_to <span style="color: #990000">:</span>supplier
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>This will work fine, because both the <tt>Supplier</tt> and the <tt>Account</tt> class are defined within the same scope. But this will not work, because <tt>Supplier</tt> and <tt>Account</tt> are defined in different scopes:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> MyApplication
  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Business
    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       has_one <span style="color: #990000">:</span>account
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Billing
    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       belongs_to <span style="color: #990000">:</span>supplier
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>To associate a model with a model in a different scope, you must specify the complete class name in your association declaration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> MyApplication
  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Business
    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"MyApplication::Billing::Account"</span>
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">module</span></span> Billing
    <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
       belongs_to <span style="color: #990000">:</span>supplier<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"MyApplication::Business::Supplier"</span>
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
</div>
<h2 id="_detailed_association_reference">4. Detailed Association Reference</h2>
<div class="sectionbody">
<div class="paragraph"><p>The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.</p></div>
<h3 id="_the_tt_belongs_to_tt_association_2">4.1. The <tt>belongs_to</tt> Association</h3>
<div class="paragraph"><p>The <tt>belongs_to</tt> association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use <tt>has_one</tt> instead.</p></div>
<h4 id="_methods_added_by_tt_belongs_to_tt">4.1.1. Methods Added by <tt>belongs_to</tt></h4>
<div class="paragraph"><p>When you declare a <tt>belongs_to</tt> assocation, the declaring class automatically gains five methods related to the association:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt><em>association</em>(force_reload = false)</tt>
</p>
</li>
<li>
<p>
<tt><em>association</em>=(associate)</tt>
</p>
</li>
<li>
<p>
<tt><em>association</em>.nil?</tt>
</p>
</li>
<li>
<p>
<tt>build<em>_association</em>(attributes = {})</tt>
</p>
</li>
<li>
<p>
<tt>create<em>_association</em>(attributes = {})</tt>
</p>
</li>
</ul></div>
<div class="paragraph"><p>In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to <tt>belongs_to</tt>. For example, given the declaration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Each instance of the order model will have these methods:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>customer
customer<span style="color: #990000">=</span>
customer<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
build_customer
create_customer</tt></pre></div></div>
<h5 id="_tt_em_association_em_force_reload_false_tt"><tt><em>association</em>(force_reload = false)</tt></h5>
<div class="paragraph"><p>The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns <tt>nil</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span> <span style="color: #990000">=</span> <span style="color: #009900">@order</span><span style="color: #990000">.</span>customer</tt></pre></div></div>
<div class="paragraph"><p>If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass <tt>true</tt> as the <tt>force_reload</tt> argument.</p></div>
<h5 id="_tt_em_association_em_associate_tt"><tt><em>association</em>=(associate)</tt></h5>
<div class="paragraph"><p>The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object&#8217;s foreign key to the same value.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order</span><span style="color: #990000">.</span>customer <span style="color: #990000">=</span> <span style="color: #009900">@customer</span></tt></pre></div></div>
<h5 id="_tt_em_association_em_nil_tt"><tt><em>association</em>.nil?</tt></h5>
<div class="paragraph"><p>The <tt><em>association</em>.nil?</tt> method returns <tt>true</tt> if there is no associated object.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@order</span><span style="color: #990000">.</span>customer<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
  <span style="color: #009900">@msg</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"No customer found for this order"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_build_em_association_em_attributes_tt"><tt>build<em>_association</em>(attributes = {})</tt></h5>
<div class="paragraph"><p>The <tt>build<em>_association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object&#8217;s foreign key will be set, but the associated object will <em>not</em> yet be saved.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span> <span style="color: #990000">=</span> <span style="color: #009900">@order</span><span style="color: #990000">.</span>build_customer<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>customer_number <span style="color: #990000">=&gt;</span> <span style="color: #993399">123</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>customer_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"John Doe"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span></tt></pre></div></div>
<h5 id="_tt_create_em_association_em_attributes_tt"><tt>create<em>_association</em>(attributes = {})</tt></h5>
<div class="paragraph"><p>The <tt>create<em>_association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object&#8217;s foreign key will be set. In addition, the associated object <em>will</em> be saved (assuming that it passes any validations).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span> <span style="color: #990000">=</span> <span style="color: #009900">@order</span><span style="color: #990000">.</span>create_customer<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>customer_number <span style="color: #990000">=&gt;</span> <span style="color: #993399">123</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>customer_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"John Doe"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span></tt></pre></div></div>
<h4 id="_options_for_tt_belongs_to_tt">4.1.2. Options for <tt>belongs_to</tt></h4>
<div class="paragraph"><p>In many situations, you can use the default behavior of <tt>belongs_to</tt> without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a <tt>belongs_to</tt> association. For example, an association with several options might look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>counter_cache <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"active = 1"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The <tt>belongs_to</tt> association supports these options:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>:class_name</tt>
</p>
</li>
<li>
<p>
<tt>:conditions</tt>
</p>
</li>
<li>
<p>
<tt>:counter_cache</tt>
</p>
</li>
<li>
<p>
<tt>:dependent</tt>
</p>
</li>
<li>
<p>
<tt>:foreign_key</tt>
</p>
</li>
<li>
<p>
<tt>:include</tt>
</p>
</li>
<li>
<p>
<tt>:polymorphic</tt>
</p>
</li>
<li>
<p>
<tt>:readonly</tt>
</p>
</li>
<li>
<p>
<tt>:select</tt>
</p>
</li>
<li>
<p>
<tt>:validate</tt>
</p>
</li>
</ul></div>
<h5 id="_tt_class_name_tt"><tt>:class_name</tt></h5>
<div class="paragraph"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is <tt>Patron</tt>, you&#8217;d set things up this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Patron"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_conditions_tt"><tt>:conditions</tt></h5>
<div class="paragraph"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"active = 1"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_counter_cache_tt"><tt>:counter_cache</tt></h5>
<div class="paragraph"><p>The <tt>:counter_cache</tt> option can be used to make finding the number of belonging objects more efficient. Consider these models:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>With these declarations, asking for the value of <tt>@customer.orders.size</tt> requires making a call to the database to perform a <tt>COUNT(*)</tt> query. To avoid this call, you can add a counter cache to the <em>belonging</em> model:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>counter_cache <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>With this declaration, Rails will keep the cache value up to date, and then return that value in response to the <tt>.size</tt> method.</p></div>
<div class="paragraph"><p>Although the <tt>:counter_cache</tt> option is specified on the model that includes the <tt>belongs_to</tt> declaration, the actual column must be added to the <em>associated</em> model. In the case above, you would need to add a column named <tt>orders_count</tt> to the <tt>Customer</tt> model. You can override the default column name if you need to:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>counter_cache <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>count_of_orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Counter cache columns are added to the containing model&#8217;s list of read-only attributes through <tt>attr_readonly</tt>.</p></div>
<h5 id="_tt_dependent_tt"><tt>:dependent</tt></h5>
<div class="paragraph"><p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the destroy method on the associated object to delete that object. If you set the <tt>:dependent</tt> option to <tt>:delete</tt>, then deleting this object will delete the associated object <em>without</em> calling its <tt>destroy</tt> method.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">You should not specify this option on a <tt>belongs_to</tt> association that is connected with a <tt>has_many</tt> association on the other class. Doing so can lead to orphaned records in your database.</td>
</tr></table>
</div>
<h5 id="_tt_foreign_key_tt"><tt>:foreign_key</tt></h5>
<div class="paragraph"><p>By convention, Rails guesses that the column used to hold the foreign key on this model is the name of the association with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Patron"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"patron_id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.</td>
</tr></table>
</div>
<h5 id="_tt_include_tt"><tt>:include</tt></h5>
<div class="paragraph"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>order
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
  has_many <span style="color: #990000">:</span>line_items
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>If you frequently retrieve customers directly from line items (<tt>@line_item.order.customer</tt>), then you can make your code somewhat more efficient by including customers in the association from line items to orders:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>order<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>customer
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
  has_many <span style="color: #990000">:</span>line_items
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">There&#8217;s no need to use <tt>:include</tt> for immediate associations - that is, if you have <tt>Order belongs_to :customer</tt>, then the customer is eager-loaded automatically when it&#8217;s needed.</td>
</tr></table>
</div>
<h5 id="_tt_polymorphic_tt"><tt>:polymorphic</tt></h5>
<div class="paragraph"><p>Passing <tt>true</tt> to the <tt>:polymorphic</tt> option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail earlier in this guide.</p></div>
<h5 id="_tt_readonly_tt"><tt>:readonly</tt></h5>
<div class="paragraph"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated object will be read-only when retrieved via the association.</p></div>
<h5 id="_tt_select_tt"><tt>:select</tt></h5>
<div class="paragraph"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">If you set the <tt>:select</tt> option on a <tt>belongs_to</tt> association, you should also set the <tt>foreign_key</tt> option to guarantee the correct results.</td>
</tr></table>
</div>
<h5 id="_tt_validate_tt"><tt>:validate</tt></h5>
<div class="paragraph"><p>If you set the <tt>:validate</tt> option to <tt>true</tt>, then associated objects will be validated whenever you save this object. By default, this is <tt>false</tt>: associated objects will not be validated when this object is saved.</p></div>
<h4 id="_when_are_objects_saved">4.1.3. When are Objects Saved?</h4>
<div class="paragraph"><p>Assigning an object to a <tt>belongs_to</tt> association does <em>not</em> automatically save the object. It does not save the associated object either.</p></div>
<h3 id="_the_has_one_association">4.2. The has_one Association</h3>
<div class="paragraph"><p>The <tt>has_one</tt> association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use <tt>belongs_to</tt> instead.</p></div>
<h4 id="_methods_added_by_tt_has_one_tt">4.2.1. Methods Added by <tt>has_one</tt></h4>
<div class="paragraph"><p>When you declare a <tt>has_one</tt> association, the declaring class automatically gains five methods related to the association:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt><em>association</em>(force_reload = false)</tt>
</p>
</li>
<li>
<p>
<tt><em>association</em>=(associate)</tt>
</p>
</li>
<li>
<p>
<tt><em>association</em>.nil?</tt>
</p>
</li>
<li>
<p>
<tt>build<em>_association</em>(attributes = {})</tt>
</p>
</li>
<li>
<p>
<tt>create<em>_association</em>(attributes = {})</tt>
</p>
</li>
</ul></div>
<div class="paragraph"><p>In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to <tt>has_one</tt>. For example, given the declaration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Each instance of the <tt>Supplier</tt> model will have these methods:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>account
account<span style="color: #990000">=</span>
account<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
build_account
create_account</tt></pre></div></div>
<h5 id="_tt_em_association_em_force_reload_false_tt_2"><tt><em>association</em>(force_reload = false)</tt></h5>
<div class="paragraph"><p>The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns <tt>nil</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@account</span> <span style="color: #990000">=</span> <span style="color: #009900">@supplier</span><span style="color: #990000">.</span>account</tt></pre></div></div>
<div class="paragraph"><p>If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass <tt>true</tt> as the <tt>force_reload</tt> argument.</p></div>
<h5 id="_tt_em_association_em_associate_tt_2"><tt><em>association</em>=(associate)</tt></h5>
<div class="paragraph"><p>The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object&#8217;s foreign key to the same value.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@suppler</span><span style="color: #990000">.</span>account <span style="color: #990000">=</span> <span style="color: #009900">@account</span></tt></pre></div></div>
<h5 id="_tt_em_association_em_nil_tt_2"><tt><em>association</em>.nil?</tt></h5>
<div class="paragraph"><p>The <tt><em>association</em>.nil?</tt> method returns <tt>true</tt> if there is no associated object.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@supplier</span><span style="color: #990000">.</span>account<span style="color: #990000">.</span><span style="font-weight: bold"><span style="color: #0000FF">nil</span></span><span style="color: #990000">?</span>
  <span style="color: #009900">@msg</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"No account found for this supplier"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_build_em_association_em_attributes_tt_2"><tt>build<em>_association</em>(attributes = {})</tt></h5>
<div class="paragraph"><p>The <tt>build<em>_association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will <em>not</em> yet be saved.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@account</span> <span style="color: #990000">=</span> <span style="color: #009900">@supplier</span><span style="color: #990000">.</span>build_account<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>terms <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Net 30"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span></tt></pre></div></div>
<h5 id="_tt_create_em_association_em_attributes_tt_2"><tt>create<em>_association</em>(attributes = {})</tt></h5>
<div class="paragraph"><p>The <tt>create<em>_association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set. In addition, the associated object <em>will</em> be saved (assuming that it passes any validations).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@account</span> <span style="color: #990000">=</span> <span style="color: #009900">@supplier</span><span style="color: #990000">.</span>create_account<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>terms <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Net 30"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span></tt></pre></div></div>
<h4 id="_options_for_tt_has_one_tt">4.2.2. Options for <tt>has_one</tt></h4>
<div class="paragraph"><p>In many situations, you can use the default behavior of <tt>has_one</tt> without any customization. But despite Rails' emphasis of convention over customization, you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a <tt>has_one</tt> association. For example, an association with several options might look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Billing"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>dependent <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>nullify
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The <tt>has_one</tt> association supports these options:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>:as</tt>
</p>
</li>
<li>
<p>
<tt>:class_name</tt>
</p>
</li>
<li>
<p>
<tt>:conditions</tt>
</p>
</li>
<li>
<p>
<tt>:dependent</tt>
</p>
</li>
<li>
<p>
<tt>:foreign_key</tt>
</p>
</li>
<li>
<p>
<tt>:include</tt>
</p>
</li>
<li>
<p>
<tt>:order</tt>
</p>
</li>
<li>
<p>
<tt>:primary_key</tt>
</p>
</li>
<li>
<p>
<tt>:readonly</tt>
</p>
</li>
<li>
<p>
<tt>:select</tt>
</p>
</li>
<li>
<p>
<tt>:source</tt>
</p>
</li>
<li>
<p>
<tt>:source_type</tt>
</p>
</li>
<li>
<p>
<tt>:through</tt>
</p>
</li>
<li>
<p>
<tt>:validate</tt>
</p>
</li>
</ul></div>
<h5 id="_tt_as_tt"><tt>:as</tt></h5>
<div class="paragraph"><p>Setting the <tt>:as</tt> option indicates that this is a polymorphic association. Polymorphic associations are discussed in detail later in this guide.</p></div>
<h5 id="_tt_class_name_tt_2"><tt>:class_name</tt></h5>
<div class="paragraph"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is Billing, you&#8217;d set things up this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Billing"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_conditions_tt_2"><tt>:conditions</tt></h5>
<div class="paragraph"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"confirmed = 1"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_dependent_tt_2"><tt>:dependent</tt></h5>
<div class="paragraph"><p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the destroy method on the associated object to delete that object. If you set the <tt>:dependent</tt> option to <tt>:delete</tt>, then deleting this object will delete the associated object <em>without</em> calling its <tt>destroy</tt> method. If you set the <tt>:dependent</tt> option to <tt>:nullify</tt>, then deleting this object will set the foreign key in the association object to <tt>NULL</tt>.</p></div>
<h5 id="_tt_foreign_key_tt_2"><tt>:foreign_key</tt></h5>
<div class="paragraph"><p>By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"supp_id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.</td>
</tr></table>
</div>
<h5 id="_tt_include_tt_2"><tt>:include</tt></h5>
<div class="paragraph"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>supplier
  belongs_to <span style="color: #990000">:</span>representative
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Representative <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>accounts
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>If you frequently retrieve representatives directly from suppliers (<tt>@supplier.account.representative</tt>), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_one <span style="color: #990000">:</span>account<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>representative
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Account <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>supplier
  belongs_to <span style="color: #990000">:</span>representative
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Representative <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>accounts
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_order_tt"><tt>:order</tt></h5>
<div class="paragraph"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause). Because a <tt>has_one</tt> association will only retrieve a single associated object, this option should not be needed.</p></div>
<h5 id="_tt_primary_key_tt"><tt>:primary_key</tt></h5>
<div class="paragraph"><p>By convention, Rails guesses that the column used to hold the primary key of this model is <tt>id</tt>. You can override this and explicitly specify the primary key with the <tt>:primary_key</tt> option.</p></div>
<h5 id="_tt_readonly_tt_2"><tt>:readonly</tt></h5>
<div class="paragraph"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated object will be read-only when retrieved via the association.</p></div>
<h5 id="_tt_select_tt_2"><tt>:select</tt></h5>
<div class="paragraph"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.</p></div>
<h5 id="_tt_source_tt"><tt>:source</tt></h5>
<div class="paragraph"><p>The <tt>:source</tt> option specifies the source association name for a <tt>has_one :through</tt> association.</p></div>
<h5 id="_tt_source_type_tt"><tt>:source_type</tt></h5>
<div class="paragraph"><p>The <tt>:source_type</tt> option specifies the source association type for a <tt>has_one :through</tt> association that proceeds through a polymorphic association.</p></div>
<h5 id="_tt_through_tt"><tt>:through</tt></h5>
<div class="paragraph"><p>The <tt>:through</tt> option specifies a join model through which to perform the query. <tt>has_one :through</tt> associations are discussed in detail later in this guide.</p></div>
<h5 id="_tt_validate_tt_2"><tt>:validate</tt></h5>
<div class="paragraph"><p>If you set the <tt>:validate</tt> option to <tt>true</tt>, then associated objects will be validated whenever you save this object. By default, this is <tt>false</tt>: associated objects will not be validated when this object is saved.</p></div>
<h4 id="_when_are_objects_saved_2">4.2.3. When are Objects Saved?</h4>
<div class="paragraph"><p>When you assign an object to a <tt>has_one</tt> association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.</p></div>
<div class="paragraph"><p>If either of these saves fails due to validation errors, then the assignment statement returns <tt>false</tt> and the assignment itself is cancelled.</p></div>
<div class="paragraph"><p>If the parent object (the one declaring the <tt>has_one</tt> association) is unsaved (that is, <tt>new_record?</tt> returns <tt>true</tt>) then the child objects are not saved.</p></div>
<div class="paragraph"><p>If you want to assign an object to a <tt>has_one</tt> association without saving the object, use the <tt>association.build</tt> method.</p></div>
<h3 id="_the_has_many_association">4.3. The has_many Association</h3>
<div class="paragraph"><p>The <tt>has_many</tt> association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.</p></div>
<h4 id="_methods_added">4.3.1. Methods Added</h4>
<div class="paragraph"><p>When you declare a <tt>has_many</tt> association, the declaring class automatically gains 13 methods related to the association:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt><em>collection</em>(force_reload = false)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>&lt;&lt;(object, ...)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.delete(object, ...)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>=objects</tt>
</p>
</li>
<li>
<p>
<tt><em>collection\_singular</em>\_ids</tt>
</p>
</li>
<li>
<p>
<tt><em>collection\_singular</em>\_ids=ids</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.clear</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.empty?</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.size</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.find(...)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.exist?(...)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.build(attributes = {}, ...)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.create(attributes = {})</tt>
</p>
</li>
</ul></div>
<div class="paragraph"><p>In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to <tt>has_many</tt>, and <tt><em>collection\_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Each instance of the customer model will have these methods:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>orders<span style="color: #990000">(</span>force_reload <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span><span style="color: #990000">)</span>
orders<span style="color: #990000">&lt;&lt;(</span>object<span style="color: #990000">,</span> <span style="color: #990000">...)</span>
orders<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>object<span style="color: #990000">,</span> <span style="color: #990000">...)</span>
orders<span style="color: #990000">=</span>objects
order_ids
order_ids<span style="color: #990000">=</span>ids
orders<span style="color: #990000">.</span>clear
orders<span style="color: #990000">.</span>empty?
orders<span style="color: #990000">.</span>size
orders<span style="color: #990000">.</span>find<span style="color: #990000">(...)</span>
orders<span style="color: #990000">.</span>exist?<span style="color: #990000">(...)</span>
orders<span style="color: #990000">.</span>build<span style="color: #990000">(</span>attributes <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">,</span> <span style="color: #990000">...)</span>
orders<span style="color: #990000">.</span>create<span style="color: #990000">(</span>attributes <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span></tt></pre></div></div>
<h5 id="_tt_em_collection_em_force_reload_false_tt"><tt><em>collection</em>(force_reload = false)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@orders</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders</tt></pre></div></div>
<h5 id="_tt_em_collection_em_lt_lt_object_tt"><tt><em>collection</em>&lt;&lt;(object, ...)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>&lt;&lt;</tt> method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders <span style="color: #990000">&lt;&lt;</span> <span style="color: #009900">@order1</span></tt></pre></div></div>
<h5 id="_tt_em_collection_em_delete_object_tt"><tt><em>collection</em>.delete(object, ...)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to <tt>NULL</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>delete<span style="color: #990000">(</span><span style="color: #009900">@order1</span><span style="color: #990000">)</span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">Objects will be in addition destroyed if they&#8217;re associated with <tt>:dependent =&gt; :destroy</tt>, and deleted if they&#8217;re associated with <tt>:dependent =&gt; :delete_all</tt>.</td>
</tr></table>
</div>
<h5 id="_tt_em_collection_em_objects_tt"><tt><em>collection</em>=objects</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.</p></div>
<h5 id="_tt_em_collection_singular_em_ids_tt"><tt><em>collection\_singular</em>\_ids</tt></h5>
<div class="paragraph"><p>The <tt><em>collection\_singular</em>\_ids</tt> method returns an array of the ids of the objects in the collection.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order_ids</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>order_ids</tt></pre></div></div>
<h5 id="_tt_em_collection_singular_em_ids_ids_tt"><tt><em>_collection\_singular</em>\_ids=ids</tt></h5>
<div class="paragraph"><p>The <tt><em>_collection\_singular</em>\_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.</p></div>
<h5 id="_tt_em_collection_em_clear_tt"><tt><em>collection</em>.clear</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with <tt>:dependent =&gt; :destroy</tt>, deletes them directly from the database if <tt>:dependent =&gt; :delete_all</tt>, and otherwise sets their foreign keys to <tt>NULL</tt>.</p></div>
<h5 id="_tt_em_collection_em_empty_tt"><tt><em>collection</em>.empty?</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.empty?</tt> method returns <tt>true</tt> if the collection does not contain any associated objects.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #FF0000">&lt;% if @customer.orders.empty? %&gt;</span>
  No Orders Found
<span style="color: #FF0000">&lt;% end %&gt;</span></tt></pre></div></div>
<h5 id="_tt_em_collection_em_size_tt"><tt><em>collection</em>.size</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order_count</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>size</tt></pre></div></div>
<h5 id="_tt_em_collection_em_find_tt"><tt><em>collection</em>.find(...)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.find</tt>.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@open_orders</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>find<span style="color: #990000">(:</span>all<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"open = 1"</span><span style="color: #990000">)</span></tt></pre></div></div>
<h5 id="_tt_em_collection_em_exist_tt"><tt><em>collection</em>.exist?(...)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.exist?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.exists?</tt>.</p></div>
<h5 id="_tt_em_collection_em_build_attributes_tt"><tt><em>collection</em>.build(attributes = {}, ...)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will <em>not</em> yet be saved.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>build<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>order_date <span style="color: #990000">=&gt;</span> Time<span style="color: #990000">.</span>now<span style="color: #990000">,</span> <span style="color: #990000">:</span>order_number <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"A12345"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span></tt></pre></div></div>
<h5 id="_tt_em_collection_em_create_attributes_tt"><tt><em>collection</em>.create(attributes = {})</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and the associated object <em>will</em> be saved (assuming that it passes any validations).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@order</span> <span style="color: #990000">=</span> <span style="color: #009900">@customer</span><span style="color: #990000">.</span>orders<span style="color: #990000">.</span>create<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>order_date <span style="color: #990000">=&gt;</span> Time<span style="color: #990000">.</span>now<span style="color: #990000">,</span> <span style="color: #990000">:</span>order_number <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"A12345"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span></tt></pre></div></div>
<h4 id="_options_for_has_many">4.3.2. Options for has_many</h4>
<div class="paragraph"><p>In many situations, you can use the default behavior for <tt>has_many</tt> without any customization. But you can alter that behavior in a number of ways. This section covers the options that you can pass when you create a <tt>has_many</tt> association. For example, an association with several options might look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>dependent <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>delete_all<span style="color: #990000">,</span> <span style="color: #990000">:</span>validate <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">false</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The <tt>has_many</tt> association supports these options:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>:as</tt>
</p>
</li>
<li>
<p>
<tt>:class_name</tt>
</p>
</li>
<li>
<p>
<tt>:conditions</tt>
</p>
</li>
<li>
<p>
<tt>:counter_sql</tt>
</p>
</li>
<li>
<p>
<tt>:dependent</tt>
</p>
</li>
<li>
<p>
<tt>:extend</tt>
</p>
</li>
<li>
<p>
<tt>:finder_sql</tt>
</p>
</li>
<li>
<p>
<tt>:foreign_key</tt>
</p>
</li>
<li>
<p>
<tt>:group</tt>
</p>
</li>
<li>
<p>
<tt>:include</tt>
</p>
</li>
<li>
<p>
<tt>:limit</tt>
</p>
</li>
<li>
<p>
<tt>:offset</tt>
</p>
</li>
<li>
<p>
<tt>:order</tt>
</p>
</li>
<li>
<p>
<tt>:primary_key</tt>
</p>
</li>
<li>
<p>
<tt>:readonly</tt>
</p>
</li>
<li>
<p>
<tt>:select</tt>
</p>
</li>
<li>
<p>
<tt>:source</tt>
</p>
</li>
<li>
<p>
<tt>:source_type</tt>
</p>
</li>
<li>
<p>
<tt>:through</tt>
</p>
</li>
<li>
<p>
<tt>:uniq</tt>
</p>
</li>
<li>
<p>
<tt>:validate</tt>
</p>
</li>
</ul></div>
<h5 id="_tt_as_tt_2"><tt>:as</tt></h5>
<div class="paragraph"><p>Setting the <tt>:as</tt> option indicates that this is a polymorphic association, as discussed earlier in this guide.</p></div>
<h5 id="_tt_class_name_tt_3"><tt>:class_name</tt></h5>
<div class="paragraph"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is <tt>Transaction</tt>, you&#8217;d set things up this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Transaction"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_conditions_tt_3"><tt>:conditions</tt></h5>
<div class="paragraph"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>confirmed_orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Order"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"confirmed = 1"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>You can also set conditions via a hash:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>confirmed_orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Order"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>confirmed <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span> <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>If you use a hash-style <tt>:conditions</tt> option, then record creation via this association will be automatically scoped using the hash. In this case, using <tt>@customer.confirmed_orders.create</tt> or <tt>@customer.confirmed_orders.build</tt> will create orders where the confirmed column has the value <tt>true</tt>.</p></div>
<h5 id="_tt_counter_sql_tt"><tt>:counter_sql</tt></h5>
<div class="paragraph"><p>Normally Rails automatically generates the proper SQL to count the association members. With the <tt>:counter_sql</tt> option, you can specify a complete SQL statement to count them yourself.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">If you specify <tt>:finder_sql</tt> but not <tt>:counter_sql</tt>, then the counter SQL will be generated by substituting <tt>SELECT COUNT(*) FROM</tt> for the <tt>SELECT ... FROM</tt> clause of your <tt>:finder_sql</tt> statement.</td>
</tr></table>
</div>
<h5 id="_tt_dependent_tt_3"><tt>:dependent</tt></h5>
<div class="paragraph"><p>If you set the <tt>:dependent</tt> option to <tt>:destroy</tt>, then deleting this object will call the destroy method on the associated objects to delete those objects. If you set the <tt>:dependent</tt> option to <tt>:delete_all</tt>, then deleting this object will delete the associated objects <em>without</em> calling their <tt>destroy</tt> method. If you set the <tt>:dependent</tt> option to <tt>:nullify</tt>, then deleting this object will set the foreign key in the associated objects to <tt>NULL</tt>.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">This option is ignored when you use the <tt>:through</tt> option on the association.</td>
</tr></table>
</div>
<h5 id="_tt_extend_tt"><tt>:extend</tt></h5>
<div class="paragraph"><p>The <tt>:extend</tt> option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.</p></div>
<h5 id="_tt_finder_sql_tt"><tt>:finder_sql</tt></h5>
<div class="paragraph"><p>Normally Rails automatically generates the proper SQL to fetch the association members. With the <tt>:finder_sql</tt> option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.</p></div>
<h5 id="_tt_foreign_key_tt_3"><tt>:foreign_key</tt></h5>
<div class="paragraph"><p>By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"cust_id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.</td>
</tr></table>
</div>
<h5 id="_tt_group_tt"><tt>:group</tt></h5>
<div class="paragraph"><p>The <tt>:group</tt> option supplies an attribute name to group the result set by, using a <tt>GROUP BY</tt> clause in the finder SQL.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>line_items<span style="color: #990000">,</span> <span style="color: #990000">:</span>through <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>group <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"orders.id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_include_tt_3"><tt>:include</tt></h5>
<div class="paragraph"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
  has_many <span style="color: #990000">:</span>line_items
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>order
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>If you frequently retrieve line items directly from customers (<tt>@customer.orders.line_items</tt>), then you can make your code somewhat more efficient by including line items in the association from customers to orders:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span><span style="font-weight: bold"><span style="color: #0000FF">include</span></span> <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>line_items
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Order <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>customer
  has_many <span style="color: #990000">:</span>line_items
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LineItem <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  belongs_to <span style="color: #990000">:</span>order
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_limit_tt"><tt>:limit</tt></h5>
<div class="paragraph"><p>The <tt>:limit</tt> option lets you restrict the total number of objects that will be fetched through an association.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>recent_orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Order"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>order <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"order_date DESC"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>limit <span style="color: #990000">=&gt;</span> <span style="color: #993399">100</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_offset_tt"><tt>:offset</tt></h5>
<div class="paragraph"><p>The <tt>:offset</tt> option lets you specify the starting offset for fetching objects via an association. For example, if you set <tt>:offset =&gt; 11</tt>, it will skip the first 11 records.</p></div>
<h5 id="_tt_order_tt_2"><tt>:order</tt></h5>
<div class="paragraph"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>order <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"date_confirmed DESC"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_primary_key_tt_2"><tt>:primary_key</tt></h5>
<div class="paragraph"><p>By convention, Rails guesses that the column used to hold the primary key of this model is <tt>id</tt>. You can override this and explicitly specify the primary key with the <tt>:primary_key</tt> option.</p></div>
<h5 id="_tt_readonly_tt_3"><tt>:readonly</tt></h5>
<div class="paragraph"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated objects will be read-only when retrieved via the association.</p></div>
<h5 id="_tt_select_tt_3"><tt>:select</tt></h5>
<div class="paragraph"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">If you specify your own <tt>:select</tt>, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.</td>
</tr></table>
</div>
<h5 id="_tt_source_tt_2"><tt>:source</tt></h5>
<div class="paragraph"><p>The <tt>:source</tt> option specifies the source association name for a <tt>has_many :through</tt> association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.</p></div>
<h5 id="_tt_source_type_tt_2"><tt>:source_type</tt></h5>
<div class="paragraph"><p>The <tt>:source_type</tt> option specifies the source association type for a <tt>has_many :through</tt> association that proceeds through a polymorphic association.</p></div>
<h5 id="_tt_through_tt_2"><tt>:through</tt></h5>
<div class="paragraph"><p>The <tt>:through</tt> option specifies a join model through which to perform the query. <tt>has_many :through</tt> associations provide a way to implement many-to-many relationships, as discussed earlier in this guide.</p></div>
<h5 id="_tt_uniq_tt"><tt>:uniq</tt></h5>
<div class="paragraph"><p>Specify the <tt>:uniq =&gt; true</tt> option to remove duplicates from the collection. This is most useful in conjunction with the <tt>:through</tt> option.</p></div>
<h5 id="_tt_validate_tt_3"><tt>:validate</tt></h5>
<div class="paragraph"><p>If you set the <tt>:validate</tt> option to <tt>false</tt>, then associated objects will not be validated whenever you save this object. By default, this is <tt>true</tt>: associated objects will be validated when this object is saved.</p></div>
<h4 id="_when_are_objects_saved_3">4.3.3. When are Objects Saved?</h4>
<div class="paragraph"><p>When you assign an object to a <tt>has_many</tt> association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.</p></div>
<div class="paragraph"><p>If any of these saves fails due to validation errors, then the assignment statement returns <tt>false</tt> and the assignment itself is cancelled.</p></div>
<div class="paragraph"><p>If the parent object (the one declaring the <tt>has_many</tt> association) is unsaved (that is, <tt>new_record?</tt> returns <tt>true</tt>) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.</p></div>
<div class="paragraph"><p>If you want to assign an object to a <tt>has_many</tt> association without saving the object, use the <tt><em>collection</em>.build</tt> method.</p></div>
<h3 id="_the_tt_has_and_belongs_to_many_tt_association_2">4.4. The <tt>has_and_belongs_to_many</tt> Association</h3>
<div class="paragraph"><p>The <tt>has_and_belongs_to_many</tt> association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.</p></div>
<h4 id="_methods_added_2">4.4.1. Methods Added</h4>
<div class="paragraph"><p>When you declare a <tt>has_and_belongs_to_many</tt> association, the declaring class automatically gains 13 methods related to the association:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt><em>collection</em>(force_reload = false)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>&lt;&lt;(object, ...)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.delete(object, ...)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>=objects</tt>
</p>
</li>
<li>
<p>
<tt><em>collection\_singular</em>\_ids</tt>
</p>
</li>
<li>
<p>
<tt><em>collection\_singular</em>\_ids=ids</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.clear</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.empty?</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.size</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.find(...)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.exist?(...)</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.build(attributes = {})</tt>
</p>
</li>
<li>
<p>
<tt><em>collection</em>.create(attributes = {})</tt>
</p>
</li>
</ul></div>
<div class="paragraph"><p>In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to <tt>has_many</tt>, and <tt><em>collection</em>\_singular</tt> is replaced with the singularized version of that symbol.. For example, given the declaration:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Part <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Each instance of the part model will have these methods:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt>assemblies<span style="color: #990000">(</span>force_reload <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">false</span></span><span style="color: #990000">)</span>
assemblies<span style="color: #990000">&lt;&lt;(</span>object<span style="color: #990000">,</span> <span style="color: #990000">...)</span>
assemblies<span style="color: #990000">.</span>delete<span style="color: #990000">(</span>object<span style="color: #990000">,</span> <span style="color: #990000">...)</span>
assemblies<span style="color: #990000">=</span>objects
assembly_ids
assembly_ids<span style="color: #990000">=</span>ids
assemblies<span style="color: #990000">.</span>clear
assemblies<span style="color: #990000">.</span>empty?
assemblies<span style="color: #990000">.</span>size
assemblies<span style="color: #990000">.</span>find<span style="color: #990000">(...)</span>
assemblies<span style="color: #990000">.</span>exist?<span style="color: #990000">(...)</span>
assemblies<span style="color: #990000">.</span>build<span style="color: #990000">(</span>attributes <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">,</span> <span style="color: #990000">...)</span>
assemblies<span style="color: #990000">.</span>create<span style="color: #990000">(</span>attributes <span style="color: #990000">=</span> <span style="color: #FF0000">{}</span><span style="color: #990000">)</span></tt></pre></div></div>
<h5 id="_additional_column_methods">Additional Column Methods</h5>
<div class="paragraph"><p>If the join table for a <tt>has_and_belongs_to_many</tt> association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/warning.png" alt="Warning" />
</td>
<td class="content">The use of extra attributes on the join table in a <tt>has_and_belongs_to_many</tt> association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a <tt>has_many :through</tt> association instead of <tt>has_and_belongs_to_many</tt>.</td>
</tr></table>
</div>
<h5 id="_tt_em_collection_em_force_reload_false_tt_2"><tt><em>collection</em>(force_reload = false)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@assemblies</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies</tt></pre></div></div>
<h5 id="_tt_em_collection_em_lt_lt_object_tt_2"><tt><em>collection</em>&lt;&lt;(object, ...)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>&lt;&lt;</tt> method adds one or more objects to the collection by creating records in the join table.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies <span style="color: #990000">&lt;&lt;</span> <span style="color: #009900">@assembly1</span></tt></pre></div></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>.</td>
</tr></table>
</div>
<h5 id="_tt_em_collection_em_delete_object_tt_2"><tt><em>collection</em>.delete(object, ...)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies<span style="color: #990000">.</span>delete<span style="color: #990000">(</span><span style="color: #009900">@assembly1</span><span style="color: #990000">)</span></tt></pre></div></div>
<h5 id="_tt_em_collection_em_objects_tt_2"><tt><em>collection</em>=objects</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.</p></div>
<h5 id="_tt_em_collection_singular_em_ids_tt_2"><tt><em>collection\_singular</em>\_ids</tt></h5>
<div class="paragraph"><p>#   Returns an array of the associated objects' ids</p></div>
<div class="paragraph"><p>The <tt><em>collection\_singular</em>\_ids</tt> method returns an array of the ids of the objects in the collection.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@assembly_ids</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assembly_ids</tt></pre></div></div>
<h5 id="_tt_em_collection_singular_em_ids_ids_tt_2"><tt><em>collection\_singular</em>\_ids=ids</tt></h5>
<div class="paragraph"><p>The <tt><em>collection\_singular</em>\_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.</p></div>
<h5 id="_tt_em_collection_em_clear_tt_2"><tt><em>collection</em>.clear</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining tableassociation. This does not destroy the associated objects.</p></div>
<h5 id="_tt_em_collection_em_empty_tt_2"><tt><em>collection</em>.empty?</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.empty?</tt> method returns <tt>true</tt> if the collection does not contain any associated objects.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #FF0000">&lt;% if @part.assemblies.empty? %&gt;</span>
  This part is <span style="font-weight: bold"><span style="color: #0000FF">not</span></span> used <span style="font-weight: bold"><span style="color: #0000FF">in</span></span> any assemblies
<span style="color: #FF0000">&lt;% end %&gt;</span></tt></pre></div></div>
<h5 id="_tt_em_collection_em_size_tt_2"><tt><em>collection</em>.size</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@assembly_count</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies<span style="color: #990000">.</span>size</tt></pre></div></div>
<h5 id="_tt_em_collection_em_find_tt_2"><tt><em>collection</em>.find(...)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.find</tt>. It also adds the additional condition that the object must be in the collection.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@new_assemblies</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies<span style="color: #990000">.</span>find<span style="color: #990000">(:</span>all<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span><span style="color: #FF0000">"created_at &gt; ?"</span><span style="color: #990000">,</span> <span style="color: #993399">2</span><span style="color: #990000">.</span>days<span style="color: #990000">.</span>ago<span style="color: #990000">])</span></tt></pre></div></div>
<h5 id="_tt_em_collection_em_exist_tt_2"><tt><em>collection</em>.exist?(...)</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.exist?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as <tt>ActiveRecord::Base.exists?</tt>.</p></div>
<h5 id="_tt_em_collection_em_build_attributes_tt_2"><tt><em>collection</em>.build(attributes = {})</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.build</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will <em>not</em> yet be saved.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@assembly</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies<span style="color: #990000">.</span>build<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>assembly_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Transmission housing"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span></tt></pre></div></div>
<h5 id="_tt_em_collection_em_create_attributes_tt_2"><tt><em>collection</em>.create(attributes = {})</tt></h5>
<div class="paragraph"><p>The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This objects will be instantiated from the passed attributes, the link through the join table will be created, and the associated object <em>will</em> be saved (assuming that it passes any validations).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="color: #009900">@assembly</span> <span style="color: #990000">=</span> <span style="color: #009900">@part</span><span style="color: #990000">.</span>assemblies<span style="color: #990000">.</span>create<span style="color: #990000">(</span><span style="color: #FF0000">{</span><span style="color: #990000">:</span>assembly_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Transmission housing"</span><span style="color: #FF0000">}</span><span style="color: #990000">)</span></tt></pre></div></div>
<h4 id="_options_for_has_and_belongs_to_many">4.4.2. Options for has_and_belongs_to_many</h4>
<div class="paragraph"><p>In many situations, you can use the default behavior for <tt>has_and_belongs_to_many</tt> without any customization. But you can alter that behavior in a number of ways. This section cover the options that you can pass when you create a <tt>has_and_belongs_to_many</tt> association. For example, an association with several options might look like this:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>uniq <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span><span style="color: #990000">,</span> <span style="color: #990000">:</span>read_only <span style="color: #990000">=&gt;</span> <span style="font-weight: bold"><span style="color: #0000FF">true</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>The <tt>has_and_belongs_to_many</tt> association supports these options:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>:association_foreign_key</tt>
</p>
</li>
<li>
<p>
<tt>:class_name</tt>
</p>
</li>
<li>
<p>
<tt>:conditions</tt>
</p>
</li>
<li>
<p>
<tt>:counter_sql</tt>
</p>
</li>
<li>
<p>
<tt>:delete_sql</tt>
</p>
</li>
<li>
<p>
<tt>:extend</tt>
</p>
</li>
<li>
<p>
<tt>:finder_sql</tt>
</p>
</li>
<li>
<p>
<tt>:foreign_key</tt>
</p>
</li>
<li>
<p>
<tt>:group</tt>
</p>
</li>
<li>
<p>
<tt>:include</tt>
</p>
</li>
<li>
<p>
<tt>:insert_sql</tt>
</p>
</li>
<li>
<p>
<tt>:join_table</tt>
</p>
</li>
<li>
<p>
<tt>:limit</tt>
</p>
</li>
<li>
<p>
<tt>:offset</tt>
</p>
</li>
<li>
<p>
<tt>:order</tt>
</p>
</li>
<li>
<p>
<tt>:readonly</tt>
</p>
</li>
<li>
<p>
<tt>:select</tt>
</p>
</li>
<li>
<p>
<tt>:uniq</tt>
</p>
</li>
<li>
<p>
<tt>:validate</tt>
</p>
</li>
</ul></div>
<h5 id="_tt_association_foreign_key_tt"><tt>:association_foreign_key</tt></h5>
<div class="paragraph"><p>By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix <tt>_id</tt> added. The <tt>:association_foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/tip.png" alt="Tip" />
</td>
<td class="content">The <tt>:foreign_key</tt> and <tt>:association_foreign_key</tt> options are useful when setting up a many-to-many self-join. For example:</td>
</tr></table>
</div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> User <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>friends<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"User"</span><span style="color: #990000">,</span>
    <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"this_user_id"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>association_foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"other_user_id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_class_name_tt_4"><tt>:class_name</tt></h5>
<div class="paragraph"><p>If the name of the other model cannot be derived from the association name, you can use the <tt>:class_name</tt> option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is <tt>Gadget</tt>, you&#8217;d set things up this way:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Gadget"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_conditions_tt_4"><tt>:conditions</tt></h5>
<div class="paragraph"><p>The <tt>:conditions</tt> option lets you specify the conditions that the associated object must meet (in the syntax used by a SQL <tt>WHERE</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"factory = 'Seattle'"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>You can also set conditions via a hash:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span> <span style="color: #990000">:</span>factory <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">'Seattle'</span> <span style="color: #FF0000">}</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>If you use a hash-style <tt>:conditions</tt> option, then record creation via this association will be automatically scoped using the hash. In this case, using <tt>@parts.assemblies.create</tt> or <tt>@parts.assemblies.build</tt> will create orders where the factory column has the value "Seattle".</p></div>
<h5 id="_tt_counter_sql_tt_2"><tt>:counter_sql</tt></h5>
<div class="paragraph"><p>Normally Rails automatically generates the proper SQL to count the association members. With the <tt>:counter_sql</tt> option, you can specify a complete SQL statement to count them yourself.</p></div>
<div class="admonitionblock">
<table><tr>
<td class="icon">
<img src="./images/icons/note.png" alt="Note" />
</td>
<td class="content">If you specify <tt>:finder_sql</tt> but not <tt>:counter_sql</tt>, then the counter SQL will be generated by substituting <tt>SELECT COUNT(*) FROM</tt> for the <tt>SELECT ... FROM</tt> clause of your <tt>:finder_sql</tt> statement.</td>
</tr></table>
</div>
<h5 id="_tt_delete_sql_tt"><tt>:delete_sql</tt></h5>
<div class="paragraph"><p>Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the <tt>:delete_sql</tt> option, you can specify a complete SQL statement to delete them yourself.</p></div>
<h5 id="_tt_extend_tt_2"><tt>:extend</tt></h5>
<div class="paragraph"><p>The <tt>:extend</tt> option specifies a named module to extend the association proxy. Association extensions are discussed in detail later in this guide.</p></div>
<h5 id="_tt_finder_sql_tt_2"><tt>:finder_sql</tt></h5>
<div class="paragraph"><p>Normally Rails automatically generates the proper SQL to fetch the association members. With the <tt>:finder_sql</tt> option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.</p></div>
<h5 id="_tt_foreign_key_tt_4"><tt>:foreign_key</tt></h5>
<div class="paragraph"><p>By convention, Rails guesses that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix <tt>_id</tt> added. The <tt>:foreign_key</tt> option lets you set the name of the foreign key directly:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> User <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>friends<span style="color: #990000">,</span> <span style="color: #990000">:</span>class_name <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"User"</span><span style="color: #990000">,</span>
    <span style="color: #990000">:</span>foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"this_user_id"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>association_foreign_key <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"other_user_id"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_group_tt_2"><tt>:group</tt></h5>
<div class="paragraph"><p>The <tt>:group</tt> option supplies an attribute name to group the result set by, using a <tt>GROUP BY</tt> clause in the finder SQL.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>group <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"factory"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_include_tt_4"><tt>:include</tt></h5>
<div class="paragraph"><p>You can use the :include option to specify second-order associations that should be eager-loaded when this association is used.</p></div>
<h5 id="_tt_insert_sql_tt"><tt>:insert_sql</tt></h5>
<div class="paragraph"><p>Normally Rails automatically generates the proper SQL to create links between the associated classes. With the <tt>:insert_sql</tt> option, you can specify a complete SQL statement to insert them yourself.</p></div>
<h5 id="_tt_join_table_tt"><tt>:join_table</tt></h5>
<div class="paragraph"><p>If the default name of the join table, based on lexical ordering, is not what you want, you can use the <tt>:join_table</tt> option to override the default.</p></div>
<h5 id="_tt_limit_tt_2"><tt>:limit</tt></h5>
<div class="paragraph"><p>The <tt>:limit</tt> option lets you restrict the total number of objects that will be fetched through an association.</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>order <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"created_at DESC"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>limit <span style="color: #990000">=&gt;</span> <span style="color: #993399">50</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_offset_tt_2"><tt>:offset</tt></h5>
<div class="paragraph"><p>The <tt>:offset</tt> option lets you specify the starting offset for fetching objects via an association. For example, if you set <tt>:offset =&gt; 11</tt>, it will skip the first 11 records.</p></div>
<h5 id="_tt_order_tt_3"><tt>:order</tt></h5>
<div class="paragraph"><p>The <tt>:order</tt> option dictates the order in which associated objects will be received (in the syntax used by a SQL <tt>ORDER BY</tt> clause).</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Parts <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_and_belongs_to_many <span style="color: #990000">:</span>assemblies<span style="color: #990000">,</span> <span style="color: #990000">:</span>order <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"assembly_name ASC"</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<h5 id="_tt_readonly_tt_4"><tt>:readonly</tt></h5>
<div class="paragraph"><p>If you set the <tt>:readonly</tt> option to <tt>true</tt>, then the associated objects will be read-only when retrieved via the association.</p></div>
<h5 id="_tt_select_tt_4"><tt>:select</tt></h5>
<div class="paragraph"><p>The <tt>:select</tt> option lets you override the SQL <tt>SELECT</tt> clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.</p></div>
<h5 id="_tt_uniq_tt_2"><tt>:uniq</tt></h5>
<div class="paragraph"><p>Specify the <tt>:uniq =&gt; true</tt> option to remove duplicates from the collection.</p></div>
<h5 id="_tt_validate_tt_4"><tt>:validate</tt></h5>
<div class="paragraph"><p>If you set the <tt>:validate</tt> option to <tt>false</tt>, then associated objects will not be validated whenever you save this object. By default, this is <tt>true</tt>: associated objects will be validated when this object is saved.</p></div>
<h4 id="_when_are_objects_saved_4">4.4.3. When are Objects Saved?</h4>
<div class="paragraph"><p>When you assign an object to a <tt>has_and_belongs_to_many</tt> association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.</p></div>
<div class="paragraph"><p>If any of these saves fails due to validation errors, then the assignment statement returns <tt>false</tt> and the assignment itself is cancelled.</p></div>
<div class="paragraph"><p>If the parent object (the one declaring the <tt>has_and_belongs_to_many</tt> association) is unsaved (that is, <tt>new_record?</tt> returns <tt>true</tt>) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.</p></div>
<div class="paragraph"><p>If you want to assign an object to a <tt>has_and_belongs_to_many</tt> association without saving the object, use the <tt><em>collection</em>.build</tt> method.</p></div>
<h3 id="_association_callbacks">4.5. Association Callbacks</h3>
<div class="paragraph"><p>Normal callbacks hook into the lifecycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a <tt>:before_save</tt> callback to cause something to happen just before an object is saved.</p></div>
<div class="paragraph"><p>Association callbacks are similar to normal callbacks, but they are triggered by events in the lifecycle of a collection. There are four available association callbacks:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>before_add</tt>
</p>
</li>
<li>
<p>
<tt>after_add</tt>
</p>
</li>
<li>
<p>
<tt>before_remove</tt>
</p>
</li>
<li>
<p>
<tt>after_remove</tt>
</p>
</li>
</ul></div>
<div class="paragraph"><p>You define association callbacks by adding options to the association declaration. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>before_add <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>check_credit_limit

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> check_credit_limit<span style="color: #990000">(</span>order<span style="color: #990000">)</span>
    <span style="color: #990000">...</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Rails passes the object being added or removed to the callback.</p></div>
<div class="paragraph"><p>You can stack callbacks on a single event by passing them as an array:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>before_add <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>check_credit_limit<span style="color: #990000">,</span> <span style="color: #990000">:</span>calculate_shipping_charges<span style="color: #990000">]</span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> check_credit_limit<span style="color: #990000">(</span>order<span style="color: #990000">)</span>
    <span style="color: #990000">...</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> calculate_shipping_charges<span style="color: #990000">(</span>order<span style="color: #990000">)</span>
    <span style="color: #990000">...</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>If a <tt>before_add</tt> callback throws an exception, the object does not get added to the collection. Similarly, if a <tt>before_remove</tt> callback throws an exception, the object does not get removed from the collection.</p></div>
<h3 id="_association_extensions">4.6. Association Extensions</h3>
<div class="paragraph"><p>You&#8217;re not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
    <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> find_by_order_prefix<span style="color: #990000">(</span>order_number<span style="color: #990000">)</span>
      find_by_region_id<span style="color: #990000">(</span>order_number<span style="color: #990000">[</span><span style="color: #993399">0</span><span style="color: #990000">..</span><span style="color: #993399">2</span><span style="color: #990000">])</span>
    <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>If you have an extension that should be shared by many associations, you can use a named extension module. For example:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">module</span></span> FindRecentExtension
  <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> find_recent
    find<span style="color: #990000">(:</span>all<span style="color: #990000">,</span> <span style="color: #990000">:</span>conditions <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span><span style="color: #FF0000">"created_at &gt; ?"</span><span style="color: #990000">,</span> <span style="color: #993399">5</span><span style="color: #990000">.</span>days<span style="color: #990000">.</span>ago<span style="color: #990000">])</span>
  <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>extend <span style="color: #990000">=&gt;</span> FindRecentExtension
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span>

<span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Supplier <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>deliveries<span style="color: #990000">,</span> <span style="color: #990000">:</span>extend <span style="color: #990000">=&gt;</span> FindRecentExtension
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>To include more than one extension module in a single association, specify an array of names:</p></div>
<div class="listingblock">
<div class="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> Customer <span style="color: #990000">&lt;</span> ActiveRecord<span style="color: #990000">::</span>Base
  has_many <span style="color: #990000">:</span>orders<span style="color: #990000">,</span> <span style="color: #990000">:</span>extend <span style="color: #990000">=&gt;</span> <span style="color: #990000">[</span>FindRecentExtension<span style="color: #990000">,</span> FindActiveExtension<span style="color: #990000">]</span>
<span style="font-weight: bold"><span style="color: #0000FF">end</span></span></tt></pre></div></div>
<div class="paragraph"><p>Extensions can refer to the internals of the association proxy using these three accessors:</p></div>
<div class="ulist"><ul>
<li>
<p>
<tt>proxy_owner</tt> returns the object that the association is a part of.
</p>
</li>
<li>
<p>
<tt>proxy_reflection</tt> returns the reflection object that describes the association.
</p>
</li>
<li>
<p>
<tt>proxy_target</tt> returns the associated object for <tt>belongs_to</tt> or <tt>has_one</tt>, or the collection of associated objects for <tt>has_many</tt> or <tt>has_and_belongs_to_many</tt>.
</p>
</li>
</ul></div>
</div>
<h2 id="_changelog">5. Changelog</h2>
<div class="sectionbody">
<div class="paragraph"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/11">Lighthouse ticket</a></p></div>
<div class="ulist"><ul>
<li>
<p>
September 28, 2008: Corrected <tt>has_many :through</tt> diagram, added polymorphic diagram, some reorganization by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> . First release version.
</p>
</li>
<li>
<p>
September 22, 2008: Added diagrams, misc. cleanup by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> (not yet approved for publication)
</p>
</li>
<li>
<p>
September 14, 2008: initial version by <a href="../authors.html#mgunderloy">Mike Gunderloy</a> (not yet approved for publication)
</p>
</li>
</ul></div>
</div>

    </div>
  </div>
</body>
</html>
